<template>
  <div>
    <!-- 报表下载 -->
    <div class="report_box">
      <!-- 导出 -->
      <el-row :gutter="20" class="gl_my_15">
        <el-col><h3 class="gl_my_5">报表</h3></el-col>
      </el-row>
      <el-row :gutter="20" class="gl_my_15">
        <el-col>
          <span style="font-size: 14px;">按项目级别选择：</span>
          <el-select v-model="eventValue.CategoryId" style="width: 150px" size="mini" filterable clearable placeholder="请选择项目" @change="changeCategoryForDown" @clear="handleClear('category')">
            <el-option v-for="item in categoryDataForDown" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select v-model="eventValue.GroupId" class="gl_ml_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择组别" @change="changeGroup" @clear="handleClear('group')" @focus="judge('category')">
            <el-option v-for="item in groupData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select v-model="eventValue.Gender" class="gl_ml_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择性别" @change="changeGender" @clear="handleClear('gender')" @focus="judge('group')">
            <el-option v-for="item in gender" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
          <el-select v-model="eventValue.EventId" class="gl_mx_10" style="width: 120px" size="mini" filterable clearable placeholder="请选择级别" @focus="judge('gender')">
            <el-option v-for="item in eventDataForDown" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="warning" size="mini" :loading="downloadBracketLoadding" @click="downloadBracket('Bracket')">按级别生成对阵表（不带场次）</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="gl_my_15">
        <el-col>
          <el-button :loading="downloadResultLoading" type="primary" size="mini" @click="downExcel('ComRegisterEntryChange')">生成级别合并表</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="demo-input-suffix gl_searchBox gl_mb_15 gl_mt_20">
      <el-row :gutter="20">
        <el-col :span="6" :lg="4">
          <p>项目选择</p>
          <el-select v-model="gameDrawQO.CategoryId" size="mini" filterable placeholder="请选择项目" @change="changeCategory()">
            <el-option v-for="(item, index) in categoryData" :key="item.id" :label="item.name" :value="index" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>组别选择</p>
          <el-select v-model="gameDrawQO.EventGroupsId" multiple size="mini" filterable clearable placeholder="请选择组别" @change="getPageData()">
            <!-- <el-option label="全部" value="" /> -->
            <el-option v-for="item in eventData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>内容搜索</p>
          <el-input v-model="gameDrawQO.NameFilter" placeholder="请输入项目名称" size="mini" clearable @change="getPageData()" />
        </el-col>
        <el-col :span="6" :lg="4">
          <p>排序</p>
          <el-select v-model="gameDrawQO.Sorting" size="mini" @change="getPageData()">
            <el-option label="正常排序" value="groupName,eventName" />
            <el-option label="人数少排序" value="registerCount" />
            <el-option label="人数多排序" value="registerCount desc" />
          </el-select>
        </el-col>
        <el-col :span="6" :lg="4">
          <p>性别</p>
          <el-select v-model="gameDrawQO.GenderCode" size="mini" @change="getPageData()">
            <el-option label="全部" value="" />
            <template v-if="currentCategoryData && currentCategoryData.genderCode === 'N'">
              <el-option label="男" value="M" />
              <el-option label="女" value="W" />
            </template>
          </el-select>
        </el-col>
        <el-col :span="18" :lg="4" class="search_btn" align="right">
          <!-- 查询按钮 -->
          <el-button type="primary" size="mini" @click="getPageData()">{{ $t('button.query') }}</el-button>
          <!-- 重置按钮 -->
          <el-button type="warning" size="mini" @click="initForm()">{{ $t('button.Reset') }}</el-button>
          <!-- <el-button type="primary" size="mini" @click="downloadBracket()">生成对阵表（不带场次）</el-button> -->
        </el-col>
      </el-row>
    </div>
    <!-- <div v-loading="drawLoading" :element-loading-text="drawLoadingText"> -->
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="19">
        <el-button type="primary" size="mini" @click="handleDraw('batch')">批量抽签</el-button>
        <template v-if="competitiveType">
          <el-button type="primary" size="mini" :disabled="(competitiveType === 'Competitive' && competitiveData.length === 0) || (competitiveType === 'NoneCompetitive' && noneCompetitiveData.length === 0)" @click="handleDraw('all')">大项一键抽签</el-button>
          <el-button type="danger" size="mini" :disabled="(competitiveType === 'Competitive' && competitiveData.length === 0) || (competitiveType === 'NoneCompetitive' && noneCompetitiveData.length === 0)" @click="handleCleanDraw('all')">大项一键清空</el-button>
          <!-- <el-tooltip class="gl_ml_5" effect="dark" content="一键操作只操作当前页的数据，如果您想操作更多数据可修改分页。" placement="top">
            <i class="el-icon-question" />
          </el-tooltip> -->
        </template>
        <el-button type="primary" size="mini" @click="handleMergeSelected()">合并选中项</el-button>
        <el-button type="primary" size="mini" @click="handleCleanDraw('selected')">清空选中项</el-button>
        <el-button type="primary" size="mini" @click="handleDrawSplit('batch')">批量拆分</el-button>
        <el-button type="primary" size="mini" @click="handleDrawweightSplit()">批量拆分（按体重）</el-button>
        <template v-if="competitiveType === 'Competitive'">
          <el-button type="primary" size="mini" @click="handleSetModule('batch')">设置竞技模型</el-button>
        </template>
        <el-tooltip class="gl_ml_5 gl_mr_10" effect="dark" content="请注意状态为已抽签的组别不允许再次进行抽签。" placement="top">
          <i class="el-icon-question" />
        </el-tooltip>
        <template v-if="showTeamAvoid">
          <span style="font-size: 14px;">是否执行同队回避：</span>
          <el-radio v-model="isTeamMemberNeedToAvoid" :label="true">是</el-radio>
          <el-radio v-model="isTeamMemberNeedToAvoid" :label="false">否</el-radio>
        </template>
      </el-col>
    </el-row>
    <template v-if="categoryData.length > 0">
      <template v-if="competitiveType === 'Competitive'">
        <el-table key="Competitive" v-loading="loading" :data="competitiveData" size="mini" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="项目名称" min-width="220">
            <template slot-scope="{row}">
              <span>{{ row.categoryName }} {{ row.groupName }}{{ row.gender.name }}{{ row.eventName }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.status')" align="center" width="120">
            <template slot-scope="{row}">
              <span :class="row.hasDrawn ? 'gl_color_success' : 'gl_color_warning'">
                <i :class="row.hasDrawn ? 'el-icon-success' : 'el-icon-remove'" />
                <span class="gl_pl_5">{{ row.hasDrawn ? '已抽签' : '未抽签' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="组别" prop="groupName" align="center" width="180" />
          <el-table-column label="性别" prop="genderCode" align="center" width="70">
            <template slot-scope="{row}">
              <span v-for="item in dict.gender" :key="item.code">
                {{ item.code === row.genderCode ? item.value : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="竞技模型" prop="kyorugiSettingName" align="center" width="190" />
          <el-table-column label="数据" align="center" width="270">
            <template slot-scope="{row}">
              <el-row :gutter="20">
                <el-col v-if="row.registerTypeCode === 'T'" :span="8">
                  组数：<span class="gl_color_primary">{{ row.registerCount }}</span>
                </el-col>
                <el-col v-else :span="8">
                  人数：<span class="gl_color_primary">{{ row.registerCount }}</span>
                </el-col>
                <el-col :span="8">
                  队伍数：<span class="gl_color_primary">{{ row.delegationCount }}</span>
                </el-col>
                <el-col :span="8">
                  总场次：<span class="gl_color_primary">{{ row.unitCount }}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="400">
            <template slot-scope="{row}">
              <template v-if="!row.hasDrawn">
                <el-button type="text" size="mini" @click="handleEditDraw(row)">修改名称</el-button>
                <el-button type="text" size="mini" @click="handleDraw('auto', row)"><span class="gl_color_warning">自动抽签</span></el-button>
                <el-button type="text" size="mini" @click="handleDraw('manual', row)"><span class="gl_color_warning">手动抽签</span></el-button>
                <el-button type="text" size="mini" @click="handleDrawSplit('row', row)"><span class="gl_color_warning">拆分</span></el-button>
                <el-button type="text" size="mini" @click="handleSetModule('row', row)"><span class="gl_color_warning">竞技模型</span></el-button>
                <el-button type="text" size="mini" @click="weightingCheck(row)">体重查看</el-button>
              </template>
              <template v-else>
                <el-button type="text" size="mini" @click="handlePreview(row)"><span class="gl_color_success">预览</span></el-button>
                <el-button type="text" size="mini" @click="changeManualDraw(row)"><span class="gl_color_warning">编辑</span></el-button>
                <el-button type="text" size="mini" @click="handleCleanDraw('row', row)"><span class="gl_color_error">清空</span></el-button>
                <el-button type="text" size="mini" @click="weightingCheck(row)">体重查看</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-if="competitiveType === 'NoneCompetitive'">
        <el-table key="NoneCompetitive" v-loading="loading" :data="noneCompetitiveData" size="mini" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="项目名称" min-width="220">
            <template slot-scope="{row}">
              <span>{{ row.categoryName }} {{ row.groupName }}{{ row.gender.name }}{{ row.eventName }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.status')" align="center" width="160">
            <template slot-scope="{row}">
              <span :class="row.hasDrawn ? 'gl_color_success' : 'gl_color_warning'">
                <i :class="row.hasDrawn ? 'el-icon-success' : 'el-icon-remove'" />
                <span class="gl_pl_5">{{ row.hasDrawn ? '已抽签' : '未抽签' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="组别" prop="groupName" align="center" width="220" />
          <el-table-column label="性别" prop="genderCode" align="center" width="100">
            <template slot-scope="{row}">
              <span v-for="item in dict.gender" :key="item.code">
                {{ item.code === row.genderCode ? item.value : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="所打章节" width="220">
            <template slot-scope="{row}">
              <span v-for="(item, index) in row.roundPoomsaeSettings" :key="item.id">
                <span>{{ item.round == '1' ? '决赛：' : item.round + '轮：' }}</span>
                <span v-for="(jtem, jndex) in item.poomsaeSettingNames" :key="jndex">
                  <span>{{ jtem }}</span>
                  <span>{{ jndex != item.poomsaeSettingNames.length - 1 ? '，' : '' }}</span>
                </span>
                <span>{{ index != row.roundPoomsaeSettings.length - 1 ? '；' : '' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="数据" align="center" width="400">
            <template slot-scope="{row}">
              <el-row :gutter="20">
                <el-col v-if="row.registerTypeCode === 'T'" :span="8">
                  组数：<span class="gl_color_primary">{{ row.registerCount }}</span>
                </el-col>
                <el-col v-else :span="8">
                  人数：<span class="gl_color_primary">{{ row.registerCount }}</span>
                </el-col>
                <el-col :span="8">
                  队伍数：<span class="gl_color_primary">{{ row.delegationCount }}</span>
                </el-col>
                <el-col :span="8">
                  总场次：<span class="gl_color_primary">{{ row.unitCount }}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="340">
            <template slot-scope="{row}">
              <template v-if="!row.hasDrawn">
                <el-button type="text" size="mini" @click="handleEditDraw(row)">修改名称</el-button>
                <el-button type="text" size="mini" @click="handleSort(row)"><span class="gl_color_warning">出场顺序</span></el-button>
                <el-button type="text" size="mini" @click="handleDrawSplit('row', row)"><span class="gl_color_warning">拆分</span></el-button>
              </template>
              <template v-else>
                <el-button type="text" size="mini" @click="handlePreview(row)"><span class="gl_color_success">预览</span></el-button>
                <el-button type="text" size="mini" @click="changeSort(row)"><span class="gl_color_warning">编辑</span></el-button>
                <el-button type="text" size="mini" @click="handleCleanDraw('row', row)"><span class="gl_color_error">清空</span></el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div align="center" class="gl_py_10">
        <el-pagination
          :current-page="gameDrawQO.Page"
          :page-size="gameDrawQO.MaxResultCount"
          :total="totalPage"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="sizeChange"
          @current-change="pageIndexChange"
        />
      </div>
    </template>
    <div v-else class="gl_noData_mockTable">
      <p>暂无数据</p>
    </div>
    <!-- </div> -->
    <!-- 合并选中项 -->
    <el-dialog :title="combineEvents_title" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogCombineEvents.visible">
      <el-form ref="refCombineEventsInput" label-width="80px" :model="dialogCombineEvents.combineEventsInput">
        <!-- 根据项目有没有组别显示是否必填 -->
        <template v-if="currentCategoryData && currentCategoryData.hasGroup">
          <el-form-item label="名称" prop="newEventName" size="mini" :rules="{ required: true, message: '合并新名称不能为空', trigger: 'blur'}">
            <el-input v-model="dialogCombineEvents.combineEventsInput.newEventName" clearable style="width: 90%;" placeholder="请输入合并新名称" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="名称" size="mini">
            <el-input v-model="dialogCombineEvents.combineEventsInput.newEventName" clearable style="width: 90%;" placeholder="请输入合并新名称" />
          </el-form-item>
        </template>
        <!-- 组别选择 -->
        <template v-if="dialogCombineEvents.eventGroupList.length > 1">
          <el-form-item label="所属组别" prop="eventGroupId" size="mini" :rules="{ required: true, message: '所属组别不能为空', trigger: 'blur'}">
            <el-select v-model="dialogCombineEvents.combineEventsInput.eventGroupId" placeholder="请选择组别" style="width: 90%;">
              <el-option v-for="item in dialogCombineEvents.eventGroupList" :key="item.groupId" :value="item.groupId" :label="item.groupName" />
            </el-select>
          </el-form-item>
        </template>
        <!-- 性别选择 -->
        <template v-if="dialogCombineEvents.genderList.length > 1">
          <el-form-item label="所属性别" prop="genderCode" size="mini" :rules="{ required: true, message: '所属性别不能为空', trigger: 'blur'}">
            <el-select v-model="dialogCombineEvents.combineEventsInput.genderCode" placeholder="请选择性别" style="width: 90%;">
              <el-option v-for="item in dialogCombineEvents.genderList" :key="item.genderCode" :value="item.genderCode" :label="item.genderName" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogCombineEvents.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitMergeSelected">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 设置竞技模型 -->
    <competitive-model ref="competitiveModel" @refreshPage="getPageData()" />
    <!-- 修改项目 -->
    <el-dialog title="修改项目名称" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogEditEvent">
      <el-form ref="refEditEvent" label-width="120px" :model="eventUpdateDto">
        <!-- 根据项目有没有组别显示是否必填 -->
        <template v-if="currentCategoryData && currentCategoryData.hasGroup">
          <el-form-item label="名称" prop="name" size="mini" :rules="{ required: true, message: '项目名称不能为空', trigger: 'blur' }">
            <el-input v-model="eventUpdateDto.name" clearable style="width: 80%;" placeholder="请输入项目名称" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="名称" size="mini">
            <el-input v-model="eventUpdateDto.name" clearable style="width: 80%;" placeholder="请输入项目名称" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogEditEvent = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitEditEvent">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 非竞技 - 出发排序  -->
    <el-dialog :title="`出场顺序 — ${sortTitleName || ''}`" width="1580px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogSortOrder.visible">
      <el-row :gutter="15" type="flex" align="middle">
        <el-col :span="13" class="gl_fs_16 gl_mb_10" style="font-weight: bold">人员列表</el-col>
        <el-col :span="9" class="gl_fs_16 gl_mb_10" style="font-weight: bold">已排序人员列表</el-col>
      </el-row>
      <el-row :gutter="15" type="flex" align="middle">
        <el-col :span="11">
          <el-table v-loading="loading" :data="dialogSortOrder.sourceTableData" size="mini" stripe height="500" @selection-change="handleDialogSourceSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column prop="competitionRegisterName" label="姓名" min-width="150" />
            <el-table-column prop="delegationName" label="所属机构" />
            <el-table-column v-if="dialogSortOrder.sourceTableData.length>0 && dialogSortOrder.sourceTableData[0].registerTypeCode==='I'" prop="registerIdCardNumber" label="身份证号" align="center" width="145" />
            <el-table-column v-if="dialogSortOrder.sourceTableData.length>0 && dialogSortOrder.sourceTableData[0].registerTypeCode==='I'" prop="registerPhoneNumber" label="手机号" width="120" align="center" />
          </el-table>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" size="mini" icon="el-icon-arrow-left" :disabled="dialogSortOrder.selectedTargetData.length === 0" @click="handleFilterTransfer('toLeft')" />
        </el-col>
        <el-col :span="1">
          <el-button type="primary" size="mini" icon="el-icon-arrow-right" :disabled="dialogSortOrder.selectedSourceData.length === 0" @click="handleFilterTransfer('toRight')" />
        </el-col>
        <el-col :span="11">
          <el-table v-loading="loading" :data="dialogSortOrder.targetTableData" size="mini" stripe height="500" @selection-change="handleDialogTargetSelection">
            <el-table-column type="selection" width="55" />
            <!-- <el-table-column type="index" width="60" align="center" /> -->
            <el-table-column prop="lotCount" label="签位" width="50" align="center">
              <template slot-scope="{$index}">
                <span>{{ $index+1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="competitionRegisterName" label="姓名" min-width="150" />
            <el-table-column prop="delegationName" label="所属机构" />
            <el-table-column v-if="dialogSortOrder.targetTableData.length>0 && dialogSortOrder.targetTableData[0].registerTypeCode==='I'" prop="registerIdCardNumber" label="身份证号" width="145" align="center" />
            <el-table-column v-if="dialogSortOrder.targetTableData.length>0 && dialogSortOrder.targetTableData[0].registerTypeCode==='I'" prop="registerPhoneNumber" label="手机号" width="120" align="center" />
            <el-table-column width="70" align="center">
              <template slot-scope="{row, $index}">
                <div class="preview_item gl_clear">
                  <div class="preview_btn gl_fr">
                    <i v-show="$index !== 0" class="preview_top el-icon-top gl_gr" @click="moveUpPreview(row, $index)" />
                    <i v-show="$index !== dialogSortOrder.targetTableData.length - 1" class="preview_bottom el-icon-bottom gl_ml_10 gl_gr" @click="moveDownPreview(row, $index)" />
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogSortOrder.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button v-if="isEidtSort" size="mini" type="primary" :loading="submitLoading" :disabled="dialogSortOrder.targetTableData.length === 0" @click="handleChangeSort()">{{ $t('button.save') }}</el-button>
        <el-button v-else size="mini" type="primary" :loading="submitLoading" :disabled="dialogSortOrder.targetTableData.length === 0" @click="handleSubmitSort()">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 自动抽签 -->
    <el-dialog title="自动抽签" width="1080px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogAutoDraw.visible">
      <el-table v-loading="loading" :data="dialogAutoDraw.tableData" size="mini" class="gl_mt_10" stripe height="500">
        <el-table-column type="index" width="60" align="center" />
        <el-table-column align="center" width="100">
          <template slot-scope="{row}">
            <span v-if="row.seed">{{ row.seed }}号种子</span>
          </template>
        </el-table-column>
        <el-table-column prop="competitionRegisterName" label="姓名" width="100" />
        <el-table-column prop="delegationName" label="所属机构" />
        <el-table-column prop="registerIdCardNumber" label="身份证号" width="150" />
        <el-table-column prop="registerPhoneNumber" label="手机号" width="120" align="center" />
        <el-table-column :label="$t('table.actions')" width="120">
          <template slot-scope="{row}">
            <el-button type="text" size="mini" @click="handleSelectSeeded(row)">
              <span>选种子</span>
            </el-button>
            <el-button v-if="row.seed" type="text" size="mini" @click="setSeed(row)">
              <span class="gl_color_error">取消</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogAutoDraw.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitAutoDraw(dialogAutoDraw.tableData, 'row')">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 自动抽签选种子 -->
    <el-dialog title="选择种子选手" width="420px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogAutoDrawChooseSeed.visible">
      <el-form ref="autoDrawChooseSeed" label-width="100px" :model="dialogAutoDrawChooseSeed.chooseSeedInput">
        <el-form-item label="种子选择" prop="seed" size="mini" :rules="{required: true, message: '请选择种子', trigger: 'blur' }">
          <el-select v-model="dialogAutoDrawChooseSeed.chooseSeedInput.seed" size="mini" placeholder="请选择种子">
            <el-option
              v-for="item in dialogAutoDrawChooseSeed.lotCount"
              :key="item.lot"
              :disabled="item.disabled"
              :value="item.lot"
              :label="item.lotName"
            >
              {{ item.lot }}号种子
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogAutoDrawChooseSeed.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="dialogAutoDrawChooseSeed.submitLoading" @click="setSeedModel()">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 手动抽签 -->
    <el-dialog title="手动抽签" width="1080px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogManualDraw.visible" top="30px">
      <against-plan v-if="dialogManualDraw.visible" :test-data="dialogManualDraw.againstData" :is-over-nums="isOverNums" />
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="24">
          <el-table v-loading="loading" :data="dialogManualDraw.tableData" size="mini" class="gl_mt_10" stripe>
            <el-table-column type="index" width="55" align="center" />
            <el-table-column prop="competitionRegisterName" label="姓名" min-width="120" />
            <el-table-column prop="delegationName" label="所属机构" min-width="140" />
            <el-table-column prop="registerIdCardNumber" label="证件号" width="190" />
            <el-table-column prop="registerPhoneNumber" label="手机号" width="120" align="center" />
            <el-table-column :label="$t('table.actions')">
              <template slot-scope="{row}" width="160">
                <el-select :value="row.lotNumber || ''" size="mini" clearable placeholder="请选择签号" @change="changeLots($event, row)">
                  <el-option v-for="item in dialogManualDraw.lotCount" :key="item.lot" :disabled="isOverNums || item.disabled" :value="`${item.lot}`">{{ item.lot }}</el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogManualDraw.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button v-if="!isOverNums" size="mini" type="primary" :loading="submitLoading" @click="handleSubmitDraw()">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 行拆分 -->
    <el-dialog title="拆分" width="1080px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogDrawSplit.visible">
      <el-table v-loading="loading" :data="dialogDrawSplit.tableData" size="mini" class="gl_mt_10" stripe height="500" @selection-change="handleDialogSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="60" align="center" />
        <el-table-column prop="competitionRegisterName" label="姓名" width="100" />
        <el-table-column prop="delegationName" label="所属机构" />
        <el-table-column prop="registerIdCardNumber" label="身份证号" width="150" />
        <el-table-column prop="registerPhoneNumber" label="手机号" width="120" align="center" />
      </el-table>
      <el-dialog width="440px" title="组别拆分" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogDrawSplit.namedVisible" append-to-body>
        <el-form ref="refSplitNamed" label-width="120px" :model="dialogDrawSplit.splitEventInput">
          <el-form-item label="组别名称" prop="newEventName" size="mini" :rules="{required: true, message: '组别名称不能为空', trigger: 'blur' }">
            <el-input v-model="dialogDrawSplit.splitEventInput.newEventName" clearable style="width: 80%;" placeholder="请输入组别名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogDrawSplit.namedVisible = false">{{ $t('button.cancel') }}</el-button>
          <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitDrawSplit('row')">{{ $t('button.save') }}</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogDrawSplit.visible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" :disabled="dialogMultipleSelection.length === 0" @click="dialogDrawSplit.namedVisible = true">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 批量拆分 -->
    <el-dialog :title="titleweight" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogDrawSplit.batchVisible">
      <el-form ref="refSplitNamed" label-width="140px" :model="dialogDrawSplit.batchSplitEventsInput">
        <el-form-item label="每组拆分最大人数" prop="maxEntriesCount" size="mini" :rules="{required: true, message: '每组拆分最大人数不能为空', trigger: 'blur' }">
          <el-input-number v-model="dialogDrawSplit.batchSplitEventsInput.maxEntriesCount" :min="1" label="请输入每组拆分最大人数" style="width: 80%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogDrawSplit.batchVisible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitDrawSplit('batch')">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 抽签预览 -->
    <el-dialog :title="'抽签预览' + (titleName ? ' - ' + titleName : '')" width="1180px" class="gl_dialog_TitleLine gameDraw" :close-on-click-modal="false" :visible.sync="dialogPreviewDraw.visible">
      <!-- <div class="title_nanme">{{ titleName }}</div> -->
      <template v-if="competitiveType === 'Competitive'">
        <against-plan v-if="dialogPreviewDraw.visible" :test-data="dialogPreviewDraw.againstData" :event-format="eventFormat" />
      </template>
      <template v-if="competitiveType === 'NoneCompetitive'">
        <el-table v-loading="loading" :data="dialogPreviewDraw.noneCompetitiveData" size="mini" class="gl_mt_10" stripe height="500">
          <el-table-column type="index" width="60" align="center" />
          <el-table-column prop="lotNumber" label="签位" width="50" align="center" />
          <el-table-column prop="competitionRegisterName" label="姓名" width="200" />
          <el-table-column prop="delegationName" label="所属机构" />
          <template v-if="registerTypeCode !== 'D' && registerTypeCode !== 'T'">
            <el-table-column prop="registerIdCardNumber" label="身份证号" width="150" />
            <el-table-column prop="registerPhoneNumber" label="手机号" width="120" align="center" />
          </template>
        </el-table>
      </template>
    </el-dialog>
    <!-- 体重查看 -->
    <weighting-check ref="weightingCheck" />
  </div>
</template>
<script>
import { getToken } from '@/lib/auth';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import { mapActions, mapState } from 'vuex';
import { translateByCode } from '@/lib/getTransData';
import AgainstPlan from '@/components/AgainstPlan';
import {
  SiSTKWEventsManagementCombineEventsInput, // 合并项目
  Api_GET_EventsManagementDrawLotsAppSeviceCompetitiveListQO, // 竞技、非竞技的查询表单一致
  SiSTKWEventsManagementManualDrawInput, // 手动抽签 / 出发顺序
  SiSTKWEventsManagementEventSetKyorugiDto, // 设置项目的竞技模型
  SiSTKWEventsManagementSplitEventInput, // 拆分单个项目
  SiSTKWEventsManagementSplitEventsInput // 批量拆分
} from '@/lib/form/game/swaggerForm';
import
{
  api_POST_EventsManagementEventIsNotWeight,
  api_POST_EventsManagementEventSplitListByWeight,
  api_GET_EventsManagementCategory, // 获取项目类别列表
  api_GET_EventsManagementCategoryHasValidEntriesCategoryListCompetitionId, // 获取有有效报项的项目类别列表
  api_GET_EventsManagementDrawLotsAppSeviceCompetitiveList, // 获取重竞技项目抽签信息
  api_GET_EventsManagementDrawLotsAppSeviceNoneCompetitiveList, // 获取非重竞技项目抽签信息
  api_POST_EventsManagementDrawLotsAppSeviceClearDrawLots, // 清除抽签
  api_POST_EventsManagementDrawLotsAppSeviceManualCompetitiveDraw, // 重竞技手动抽签
  api_PUT_EventsManagementDrawLotsAppSeviceDrawLots, // 手动修改抽签结果
  api_POST_EventsManagementDrawLotsAppSeviceManualNoneCompetitiveDraw, // 非重竞技手动抽签
  api_POST_EventsManagementDrawLotsAppSeviceAutoCompetitiveDraw, // 重竞技自动抽签
  api_POST_EventsManagementDrawLotsAppSeviceAutoNoneCompetitiveDraw, // 非重竞技自动抽签
  api_GET_EventsManagementDrawLotsAppSeviceDrawLotsResultEventId, // 获取抽签结果
  api_PUT_EventsManagementEntryEntrySeedEntryId, // 设置种子号
  api_POST_EventsManagementEventCombine, // 合并项目
  api_POST_EventsManagementEventSetKyorugi, // 提交设置竞技模型
  api_POST_EventsManagementEventIdChangeName, // 修改项目
  api_GET_EventsManagementEventIdEntryRegisters, // 获取项目报项人员/队伍列表
  api_POST_EventsManagementEventIdSplit, // 拆分单个项目
  api_POST_EventsManagementEventSplitList, // 批量拆分
  api_POST_EventsManagementDrawLotsAppSeviceBatchClearDrawLotsCategoryId, // 对当前赛事清空抽签
  api_POST_EventsManagementDrawLotsAppSeviceBatchDraw, // 对当前赛事所有技项目进行抽签
  api_GET_EventsManagementDrawLotsAppSeviceIdUndrawnEntryRegisters // 获取未抽签项目报项人员/队伍列表
} from '@/extend/api/gameswaggerApi/app';
import CompetitiveModel from './competitiveModel/competitiveModelList.vue';
import WeightingCheck from './competitiveModel/weightingCheck.vue';
import { deepCopy } from '@/lib';
export default {
  name: 'GameDraw',
  components: {
    AgainstPlan,
    CompetitiveModel,
    WeightingCheck
  },
  data() {
    return {
      titleweight: '批量拆分',
      tokenInfo: getToken(),
      competitiveType: '', // 竞技、非竞技
      categoryData: [], // 项目
      eventData: [], // 组别
      eventFormat: false, // 是否有铜牌赛
      isTeamMemberNeedToAvoid: true, // 同队回避
      isSeedNeedToAvoid: true,
      gameDrawQO: new Api_GET_EventsManagementDrawLotsAppSeviceCompetitiveListQO(),
      competitiveData: [],
      noneCompetitiveData: [],
      tableRow: {},
      multipleSelection: [],
      dialogMultipleSelection: [],
      // 设置竞技模型
      dialogSetModule: {
        type: '',
        visible: false,
        moduleData: [],
        previewVisible: false,
        selectedModule: '',
        moduleDto: new SiSTKWEventsManagementEventSetKyorugiDto(),
        currentPreview: null
      },
      // 修改名称
      dialogEditEvent: false,
      eventUpdateDto: {
        name: ''
      },
      // 自动抽签
      dialogAutoDraw: {
        visible: false,
        tableData: []
      },
      // 自动抽签选择种子
      dialogAutoDrawChooseSeed: {
        visible: false,
        chooseSeedInput: {
          entryId: '',
          seed: ''
        },
        lotCount: [],
        submitLoading: false
      },
      // 排序
      dialogSortOrder: {
        visible: false,
        sourceTableData: [], // 获取的可报名列表
        selectedSourceData: [], // 左侧选中的源数据
        targetTableData: [], // 最终选中的列表
        selectedTargetData: [] // 右侧选中的源数据
      },
      // 手动抽签
      dialogManualDraw: {
        visible: false,
        tableData: [],
        currentLot: null,
        manualDrawInput: new SiSTKWEventsManagementManualDrawInput(),
        lotCount: [],
        // 初始对阵图数据 未排序
        tableDataAgainst: [],
        // 对阵图数据
        againstData: []
      },
      // 拆分
      dialogDrawSplit: {
        type: '',
        visible: false,
        tableData: [],
        namedVisible: false,
        splitEventInput: new SiSTKWEventsManagementSplitEventInput(),
        batchVisible: false,
        batchSplitEventsInput: new SiSTKWEventsManagementSplitEventsInput()
      },
      // 合并项目
      dialogCombineEvents: {
        visible: false,
        eventGroupList: [],
        genderList: [],
        combineEventsInput: new SiSTKWEventsManagementCombineEventsInput()
      },
      // 预览抽签
      dialogPreviewDraw: {
        visible: false,
        competitiveData: [],
        noneCompetitiveData: [],
        againstData: []
      },
      currentPage: 1,
      totalPage: 0,
      loading: false,
      submitLoading: false,
      dialogLoading: false,
      downloadResultLoadding: false,
      downloadBracketLoadding: false,
      registerTypeCode: 'I',
      currentCategoryData: null, // 当前选中的项目数据
      eventValue: {
        CategoryId: '',
        GroupId: '',
        Gender: '',
        EventId: ''
      },
      groupData: [],
      gender: [],
      eventDataForDown: [],
      categoryDataForDown: [],
      titleName: '',
      sortTitleName: '',
      showTeamAvoid: true, // 控制是否执行同队回避 显示
      matchMap: [2, 4, 8, 16, 32, 64], // 对阵图对阵数量
      drawLoading: false,
      fullscreenLoading: '',
      downloadResultLoading: false,
      drawLoadingText: '',
      currentcategoryID: '',
      combineEvents_title: '',
      drawLotsResult: [], // 已抽签的人数据
      undrawnEntryRegisters: [], // 未抽签的人数据
      isOverNums: false, // 判断竞技的编辑里新报名的人员是否超过了原先的对阵图人数
      isEidtDraw: false, // 判断是编辑抽签还是手动抽签
      isEidtSort: false // 判断是编辑出发顺序
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  watch: {
    'dialogSetModule.visible': function(val) {
      if (!val) {
        this.dialogSetModule.selectedModule = '';
      }
    },
    'dialogCombineEvents.visible'(val) {
      if (!val) {
        this.$refs['refCombineEventsInput'].resetFields();
        this.dialogCombineEvents.combineEventsInput = new SiSTKWEventsManagementCombineEventsInput();
      }
    },
    dialogEditEvent(val) {
      if (!val) {
        this.$refs['refEditEvent'].resetFields();
        this.eventUpdateDto.name = '';
      }
    }
    // 'dialogSortOrder.visible'(val) {
    //   if (val) {
    //     this.dialogSortOrder.targetTableData = [];
    //   }
    // }
  },
  created() {
    this.getDict();
    this.getEventList();
    api_GET_EventsManagementCategoryHasValidEntriesCategoryListCompetitionId(this.$route.params.id).then(res => {
      this.categoryData = res;
      console.log(this.categoryData);
      if (this.categoryData.length > 0) {
        this.competitiveType = this.categoryData[0].eventTypeCode;
        this.gameDrawQO.CategoryId = 0; // 绑定的是index
        this.gameDrawQO.Sorting = 'groupName,eventName';
        this.eventData = this.categoryData[0].eventGroups;
        console.log('eventData', this.eventData);
        this.changeCategory();
      }
    });
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    initForm() {
      this.gameDrawQO = new Api_GET_EventsManagementDrawLotsAppSeviceCompetitiveListQO();
      this.isTeamMemberNeedToAvoid = true;
      this.isSeedNeedToAvoid = true;
      if (this.categoryData.length > 0) {
        this.competitiveType = this.categoryData[0].eventTypeCode;
        this.gameDrawQO.CategoryId = 0; // 绑定的是index
        this.gameDrawQO.Sorting = 'groupName,eventName';
        this.eventData = this.categoryData[0].eventGroups;
        this.changeCategory();
      }
    },
    // 切换项目 —— 竞技、非竞技是从项目接口里带出来的
    changeCategory() {
      const categoryData = this.categoryData[this.gameDrawQO.CategoryId];
      console.log(categoryData);
      this.currentcategoryID = categoryData.id;
      this.showTeamAvoid = categoryData.eventTypeCode !== 'NoneCompetitive';
      this.currentCategoryData = categoryData;
      this.competitiveType = categoryData.eventTypeCode;
      // this.gameDrawQO.EventGroupsId = [''];
      this.gameDrawQO.GenderCode = '';
      this.eventData = categoryData.eventGroups;
      console.log(categoryData);
      // this.groupData = categoryData;
      this.getPageData();
    },
    // 获取表格数据
    getPageData(page) {
      this.loading = true;
      this.gameDrawQO.Page = page || 1;
      this.gameDrawQO.SkipCount = (this.gameDrawQO.Page - 1) * this.gameDrawQO.MaxResultCount;
      const _gameDrawQO = JSON.parse(JSON.stringify(this.gameDrawQO));
      _gameDrawQO.CompetitionId = this.$route.params.id;
      _gameDrawQO.CategoryId = this.categoryData[this.gameDrawQO.CategoryId].id;
      if (this.competitiveType === 'Competitive') {
        api_GET_EventsManagementDrawLotsAppSeviceCompetitiveList(_gameDrawQO).then(res => {
          this.competitiveData = res.items;
          this.totalPage = res.totalCount;
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }
      if (this.competitiveType === 'NoneCompetitive') {
        api_GET_EventsManagementDrawLotsAppSeviceNoneCompetitiveList(_gameDrawQO).then(res => {
          this.noneCompetitiveData = res.items;
          this.totalPage = res.totalCount;
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }
    },
    sizeChange(MaxResultCount) {
      this.gameDrawQO.MaxResultCount = MaxResultCount;
      this.getPageData();
    },
    pageIndexChange(currentPage) {
      this.getPageData(currentPage);
    },
    // 表格选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 抽签
     * @param {string} type 一键抽签=all 批量抽签=batch 自动抽签=auto 手动抽签=manual
     * @param {object} row 操作单行数据的row值
    */
    handleDraw(type, row) {
      const _this = this;
      _this.isEidtDraw = false;
      _this.isOverNums = false;
      if (type === 'all') {
        // 一键抽签
        this.$confirm(`您确定要为"${this.currentCategoryData.name}"大项所有组别抽签吗？`, '大项一键抽签', {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          // _this.drawLoading = true;
          // _this.drawLoadingText = '一键抽签中';
          _this.fullscreenLoading = this.$loading({
            lock: true,
            text: '一键抽签中,请稍候...'
          });
          this.handleAllDraw();
        });
      } else if (type === 'batch') {
        // 批量抽签
        if (this.multipleSelection.length > 0) {
          this.$confirm(`你确定要进行批量抽签操作吗？`, '批量抽签', {
            confirmButtonText: translateByCode('alert.confirm'),
            cancelButtonText: translateByCode('alert.cancel'),
            type: 'warning'
          }).then(() => {
            this.handleSubmitAutoDraw(this.multipleSelection, 'batch'); // 批量抽签直接走自动抽签
          });
        } else {
          this.$message({ type: 'warning', message: '请至少先勾选一条数据，再进行操作！' });
        }
      } else if (type === 'auto') {
        // 自动抽签
        this.handleAutoDraw(row);
      } else if (type === 'manual') {
        // 手动抽签
        this.handleManualDraw(row);
      }
    },
    /**
     * 清空抽签
     * @param {string} type 一键清空=all 行清空=row 清空选中项=selected
     * @param {object} row 操作单行数据的row值
    */
    handleCleanDraw(type, row) {
      const _this = this;
      let _input = [];
      if (type === 'all') {
        // 一键清空
        this.$confirm(`您确定要一键清空"${this.currentCategoryData.name}"所有组别的抽签吗？`, '大项一键清空抽签', {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          // _this.drawLoading = true;
          // _this.drawLoadingText = '一键清空抽签中';
          _this.fullscreenLoading = this.$loading({
            lock: true,
            text: '一键清空抽签中,请稍候...'
          });
          this.handleCleanAll();
        });
      } else if (type === 'row') {
        // 行清空
        this.$confirm(`你确定要清空【${row.groupName}】的抽签吗？`, '清空抽签', {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          type: 'warning'
        }).then(() => {
          _input.push(row.eventId);
          this.handleCleanSelected(_input);
        });
      } else if (type === 'selected') {
        // 清空选中项
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'warning', message: '请至少先勾选一条数据，再进行操作！' });
          return;
        }
        this.$confirm(`你确定要清空选中的抽签吗？`, '清空抽签', {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          type: 'warning'
        }).then(() => {
          _input = this.multipleSelection.map(item => item.eventId);
          this.handleCleanSelected(_input);
        });
      }
    },
    handleCleanSelected(input) {
      api_POST_EventsManagementDrawLotsAppSeviceClearDrawLots({ eventsId: input }).then(res => {
        this.getPageData();
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: '操作失败！' + error.error.message });
      });
    },
    // 一键清空
    handleCleanAll() {
      const _this = this;
      api_POST_EventsManagementDrawLotsAppSeviceBatchClearDrawLotsCategoryId(this.currentcategoryID).then(res => {
        this.getPageData();
        this.$message({ type: 'success', message: '操作成功' });
        // this.drawLoading = false;
        _this.fullscreenLoading.close();
      }, error => {
        this.$message({ type: 'error', message: '操作失败！' + error.error.message });
        // this.drawLoading = false;
        _this.fullscreenLoading.close();
      });
    },
    /**
     * 合并选中项
    */
    handleMergeSelected() {
      console.log(this.multipleSelection);
      if (this.multipleSelection.length > 1) {
        // 判断选中不同组别时的展示
        const eventGroupIdList = [];
        const eventGroupList = [];
        // eslint-disable-next-line no-unused-vars
        let _name = '';
        // eslint-disable-next-line no-unused-vars
        let _hasDrawn = false;
        this.multipleSelection.forEach(item => {
          if (item.hasDrawn) {
            _hasDrawn = true;
            _name = item.categoryName + ' ' + item.groupName + item.gender.name + item.eventName;
          }
          if (!eventGroupIdList.includes(item.groupId)) {
            eventGroupIdList.push(item.groupId);
            eventGroupList.push({
              groupId: item.groupId,
              groupName: item.groupName
            });
          }
        });
        if (_hasDrawn) {
          this.$message({ type: 'warning', message: `项目[${_name}]已抽签，不可合并！` });
        } else {
          this.dialogCombineEvents.eventGroupList = eventGroupList;
          if (eventGroupList.length === 1) {
            this.dialogCombineEvents.combineEventsInput.eventGroupId = eventGroupList[0].groupId;
          }
          // 判断选中不同组别时的展示
          const genderCodeList = [];
          const genderList = [];
          this.multipleSelection.forEach(item => {
            if (!genderCodeList.includes(item.genderCode)) {
              genderCodeList.push(item.genderCode);
              genderList.push({
                genderCode: item.genderCode,
                genderName: item.genderCode === 'W' ? '女' : '男'
              });
            }
          });
          this.dialogCombineEvents.genderList = genderList;
          if (genderList.length === 1) {
            this.dialogCombineEvents.combineEventsInput.genderCode = genderList[0].genderCode;
          }
          if (this.currentCategoryData.hasGroup) {
            this.combineEvents_title = '合并选中项';
          } else {
            this.combineEvents_title = '修改项目名称';
          }
          this.dialogCombineEvents.visible = true;
        }
      } else {
        this.$message({ type: 'warning', message: '请至少先勾选两条数据，再进行操作！' });
      }
    },
    // 提交 —— 合并选中项
    handleSubmitMergeSelected() {
      this.$refs['refCombineEventsInput'].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.dialogCombineEvents.combineEventsInput.eventIds = this.multipleSelection.map(item => item.eventId);
          api_POST_EventsManagementEventCombine(this.dialogCombineEvents.combineEventsInput).then(res => {
            this.submitLoading = false;
            this.getPageData();
            this.dialogCombineEvents.visible = false;
            this.$message({ type: 'success', message: '操作成功' });
          }, error => {
            this.submitLoading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 拆分
     * @param {string} type 批量拆分=batch 行拆分=row
     * @param {object} row 操作单行数据的row值
    */
    handleDrawSplit(type, row) {
      this.dialogDrawSplit.type = type;
      if (type === 'batch') {
        // 批量拆分
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'warning', message: '请至少先勾选一条数据，再进行操作！' });
          return;
        }
        this.titleweight = '批量拆分'
        this.dialogDrawSplit.batchVisible = true;

      }
      if (type === 'row') {
        this.loading = true;
        this.tableRow = row;
        this.dialogDrawSplit.splitEventInput = new SiSTKWEventsManagementSplitEventInput();
        this.getEntryRegistersData(row).then(res => {
          this.loading = false;
          this.dialogDrawSplit.tableData = res.items;
          for (let i = 0; i < this.dialogDrawSplit.tableData.length; i++) {
            const item = this.dialogDrawSplit.tableData[i];
            if (item.registerNames && item.registerNames.length > 0) {
              for (let j = 0; j < item.registerNames.length; j++) {
                if (j === 0) {
                  item.competitionRegisterName = item.registerNames[j];
                } else {
                  item.competitionRegisterName += '/' + item.registerNames[j];
                }
              }
            }
          }
          console.log(this.dialogDrawSplit.tableData);
          this.dialogDrawSplit.visible = true;
        });
      }
    },
    // dialog里面的表格选中
    handleDialogSelectionChange(val) {
      this.dialogMultipleSelection = val;
    },
    // 提交 —— 批量拆分/行拆分 type 批量抽签=batch； 单行设置=row；
    handleSubmitDrawSplit(type) {
      if(this.titleweight === '批量拆分(按体重)') {
        type = 'weight'
      }
      this.$refs['refSplitNamed'].validate(valid => {
        if (valid) {
          if (type === 'row') {
            this.dialogDrawSplit.splitEventInput.entryIds = this.dialogMultipleSelection.map(item => item.entryId);
            api_POST_EventsManagementEventIdSplit(this.tableRow.eventId, this.dialogDrawSplit.splitEventInput).then(res => {
              this.getPageData();
              this.dialogDrawSplit.namedVisible = false;
              this.dialogDrawSplit.visible = false;
              this.$message({ type: 'success', message: '操作成功' });
            }, error => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          }
          if (type === 'batch') {
            this.dialogDrawSplit.batchSplitEventsInput.isTeamMemberNeedToAvoid = true;
            this.dialogDrawSplit.batchSplitEventsInput.eventIds = this.multipleSelection.map(item => item.eventId);
            api_POST_EventsManagementEventSplitList(this.dialogDrawSplit.batchSplitEventsInput).then(res => {
              this.getPageData();
              this.dialogDrawSplit.batchVisible = false;
              this.$message({ type: 'success', message: '操作成功' });
              this.dialogDrawSplit.batchSplitEventsInput.maxEntriesCount = 1;
            }, error => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          }
          if (type === 'weight') {
            this.dialogDrawSplit.batchSplitEventsInput.isTeamMemberNeedToAvoid = true;
            this.dialogDrawSplit.batchSplitEventsInput.eventIds = this.multipleSelection.map(item => item.eventId);
            api_POST_EventsManagementEventSplitListByWeight(this.dialogDrawSplit.batchSplitEventsInput).then(res => {
              this.getPageData();
              this.dialogDrawSplit.batchVisible = false;
              this.$message({ type: 'success', message: '操作成功' });
              this.dialogDrawSplit.batchSplitEventsInput.maxEntriesCount = 1;
            }, error => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            });
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 设置竞技模型
     * @param {string} type 批量设置=batch 行设置=row
     * @param {object} row 操作单行数据的row值
    */
    handleSetModule(type, row) {
      let eventsId = [];
      if (type === 'batch') {
        if (this.multipleSelection.length === 0) {
          this.$message({ type: 'warning', message: '请至少先勾选一条数据，再进行操作！' });
          return;
        }
        eventsId = this.multipleSelection.map(item => item.eventId);
      }
      if (type === 'row') {
        this.tableRow = row;
        eventsId = [this.tableRow.eventId];
      }
      this.$refs.competitiveModel.open(eventsId, row);
    },
    // 预览竞技模型
    handlePreviewModule(val) {
      this.dialogSetModule.previewVisible = true;
      this.dialogSetModule.currentPreview = val;
    },
    // 提交 —— 设置竞技模型
    handleSubmitModule() {
      this.dialogSetModule.moduleDto.kyorugiSettingId = this.dialogSetModule.selectedModule;
      if (this.dialogSetModule.type === 'batch') {
        // 批量设置 —— 处理参数
        this.dialogSetModule.moduleDto.eventsId = this.multipleSelection.map(item => item.eventId);
      }
      if (this.dialogSetModule.type === 'row') {
        this.dialogSetModule.moduleDto.eventsId.push(this.tableRow.eventId);
      }
      this.submitLoading = true;
      api_POST_EventsManagementEventSetKyorugi(this.dialogSetModule.moduleDto).then(res => {
        this.submitLoading = false;
        this.getPageData();
        this.dialogSetModule.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    /**
     * 修改名称
     * @param {object} row 操作单行数据的row值
    */
    handleEditDraw(row) {
      this.tableRow = row;
      this.dialogEditEvent = true;
    },
    // 提交 —— 抽签名称
    handleSubmitEditEvent() {
      this.$refs['refEditEvent'].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          api_POST_EventsManagementEventIdChangeName(this.tableRow.eventId, this.eventUpdateDto).then(res => {
            this.submitLoading = false;
            this.getPageData(this.gameDrawQO.Page);
            this.dialogEditEvent = false;
            this.$message({ type: 'success', message: '操作成功' });
          }, error => {
            this.submitLoading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 出场顺序
     * @param {object} row 操作单行数据的row值
    */
    handleSort(row) {
      this.tableRow = row;
      this.isEidtSort = false;
      this.dialogSortOrder.targetTableData = [];
      this.sortTitleName = row.categoryName + ' ' + row.groupName + row.gender.name + row.eventName;
      this.getEntryRegistersData(row).then(res => {
        this.dialogSortOrder.sourceTableData = res.items;
        for (let i = 0; i < this.dialogSortOrder.sourceTableData.length; i++) {
          const item = this.dialogSortOrder.sourceTableData[i];
          if (item.registerNames && item.registerNames.length > 0) {
            for (let j = 0; j < item.registerNames.length; j++) {
              if (j === 0) {
                item.competitionRegisterName = item.registerNames[j];
              } else {
                item.competitionRegisterName += '/' + item.registerNames[j];
              }
            }
          }
        }
        console.log(this.dialogSortOrder.sourceTableData);
        this.dialogSortOrder.visible = true;
      });
    },
    /**
     * 编辑出场顺序
     * @param {object} row 操作单行数据的row值
    */
    changeSort(row) {
      // 判断是否是铜牌赛
      if (row.eventFormatCode === 'BronzeMedal') {
        this.eventFormat = true;
      } else {
        this.eventFormat = false;
      }

      const _this = this;
      if (row.isEditable) {
        this.tableRow = row;
        this.isEidtSort = true;
        this.dialogSortOrder.targetTableData = [];
        _this.sortTitleName = row.categoryName + ' ' + row.groupName + row.gender.name + row.eventName;
        api_GET_EventsManagementDrawLotsAppSeviceDrawLotsResultEventId(row.eventId).then(res => {
          _this.dialogSortOrder.targetTableData = res;
          for (let i = 0; i < _this.dialogSortOrder.targetTableData.length; i++) {
            const item = _this.dialogSortOrder.targetTableData[i];
            if (item.registerNames && item.registerNames.length > 0) {
              for (let j = 0; j < item.registerNames.length; j++) {
                if (j === 0) {
                  item.competitionRegisterName = item.registerNames[j];
                } else {
                  item.competitionRegisterName += '/' + item.registerNames[j];
                }
              }
            }
          }
          _this.getUndrawnEntryRegisters(row).then(res1 => {
            _this.dialogSortOrder.sourceTableData = res1;
            for (let i = 0; i < _this.dialogSortOrder.sourceTableData.length; i++) {
              const item = _this.dialogSortOrder.sourceTableData[i];
              if (item.registerNames && item.registerNames.length > 0) {
                for (let j = 0; j < item.registerNames.length; j++) {
                  if (j === 0) {
                    item.competitionRegisterName = item.registerNames[j];
                  } else {
                    item.competitionRegisterName += '/' + item.registerNames[j];
                  }
                }
              }
            }
            console.log('left', _this.dialogSortOrder.sourceTableData);
            console.log('right', _this.dialogSortOrder.targetTableData);
            this.dialogSortOrder.visible = true;
          });
        }, (error) => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      } else {
        this.$message({ type: 'warning', message: '此项目已开赛，不能进行编辑操作！' });
      }
    },
    // 左侧源数据
    handleDialogSourceSelection(val) {
      this.dialogSortOrder.selectedSourceData = val;
    },
    // 右侧已选中数据
    handleDialogTargetSelection(val) {
      this.dialogSortOrder.selectedTargetData = val;
    },
    handleFilterTransfer(type) {
      if (type === 'toRight') {
        this.dialogSortOrder.targetTableData = this.processTransferData(this.dialogSortOrder.sourceTableData, this.dialogSortOrder.targetTableData, this.dialogSortOrder.selectedSourceData);
      }
      if (type === 'toLeft') {
        this.dialogSortOrder.sourceTableData = this.processTransferData(this.dialogSortOrder.targetTableData, this.dialogSortOrder.sourceTableData, this.dialogSortOrder.selectedTargetData);
      }
      console.log(this.dialogSortOrder.targetTableData);
    },
    // 穿梭框函数
    processTransferData(source, target, selected) {
      for (let i = 0; i < source.length; i++) {
        const item = source[i];
        if (selected.find(jtem => jtem === item)) {
          target = target.concat(source.splice(i, 1));
          i--;
        }
      }
      return target;
    },
    // 排序 上移下移
    moveUpPreview (item, index) {
      const _previewList = this.dialogSortOrder.targetTableData;
      if (index === 0) return;
      const _spliceItem = _previewList.splice(index, 1);
      _previewList.splice(index - 1, 0, _spliceItem[0]);
    },
    moveDownPreview (item, index) {
      const _previewList = this.dialogSortOrder.targetTableData;
      if (_previewList.length - 1 === index) return;
      const _spliceItem = _previewList.splice(index, 1);
      _previewList.splice(index + 1, 0, _spliceItem[0]);
    },
    // 提交 —— 出场顺序
    handleSubmitSort() {
      this.dialogManualDraw.manualDrawInput.eventId = this.tableRow.eventId;
      this.dialogManualDraw.manualDrawInput.items = [];
      this.dialogSortOrder.targetTableData.filter((item, index) => {
        this.dialogManualDraw.manualDrawInput.items.push({
          registerId: item.competitionRegisterId,
          lotNumber: index + 1
        });
      });
      api_POST_EventsManagementDrawLotsAppSeviceManualNoneCompetitiveDraw(this.dialogManualDraw.manualDrawInput).then(res => {
        this.getPageData(this.gameDrawQO.Page);
        this.dialogSortOrder.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 提交 —— 更改出场顺序
    handleChangeSort() {
      this.dialogManualDraw.manualDrawInput.eventId = this.tableRow.eventId;
      this.dialogManualDraw.manualDrawInput.items = [];
      this.dialogSortOrder.targetTableData.filter((item, index) => {
        this.dialogManualDraw.manualDrawInput.items.push({
          registerId: item.competitionRegisterId,
          lotNumber: index + 1
        });
      });
      api_PUT_EventsManagementDrawLotsAppSeviceDrawLots(this.dialogManualDraw.manualDrawInput).then(res => {
        this.getPageData(this.gameDrawQO.Page);
        this.dialogSortOrder.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    /**
     * 自动抽签
     * @param {object} row 操作单行数据的row值
    */
    handleAutoDraw(row) {
      this.loading = false;
      this.tableRow = row;
      // 处理签位号
      this.dialogAutoDrawChooseSeed.lotCount = [];
      for (let i = 0; i < row.registerCount; i++) {
        this.dialogAutoDrawChooseSeed.lotCount.push({
          lot: i + 1,
          lotName: `${i + 1}号种子`,
          disabled: false
        });
      }
      console.log(this.dialogAutoDrawChooseSeed.lotCount);
      this.getEntryRegistersData(row).then(res => {
        this.loading = false;
        this.dialogAutoDraw.tableData = res.items || [];
        console.log(this.dialogAutoDraw.tableData);
        for (let i = 0; i < this.dialogAutoDraw.tableData.length; i++) {
          const item = this.dialogAutoDraw.tableData[i];
          if (item.registerNames && item.registerNames.length > 0) {
            for (let j = 0; j < item.registerNames.length; j++) {
              if (j === 0) {
                item.competitionRegisterName = item.registerNames[j];
              } else {
                item.competitionRegisterName += '/' + item.registerNames[j];
              }
            }
          }
          if (item.seed && item.seed <= this.dialogAutoDrawChooseSeed.lotCount.length) {
            this.dialogAutoDrawChooseSeed.lotCount[item.seed - 1].disabled = true;
          }
        }
        this.dialogAutoDraw.visible = true;
      });
    },
    // 选/取消 种子
    handleSelectSeeded(row) {
      this.dialogAutoDrawChooseSeed.chooseSeedInput.entryId = row.entryId;
      this.dialogAutoDrawChooseSeed.chooseSeedInput.seed = row.seed || '';
      this.dialogAutoDrawChooseSeed.visible = true;
    },
    // 选择种子选手里的设置种子
    setSeedModel() {
      this.$refs.autoDrawChooseSeed.validate(valid => {
        if (!valid) return;
        this.dialogAutoDrawChooseSeed.submitLoading = true;
        api_PUT_EventsManagementEntryEntrySeedEntryId(
          this.dialogAutoDrawChooseSeed.chooseSeedInput.entryId,
          { seed: this.dialogAutoDrawChooseSeed.chooseSeedInput.seed }
        ).then(res => {
          this.handleAutoDraw(this.tableRow);
          this.$message({ type: 'success', message: '操作成功' });
          this.dialogAutoDrawChooseSeed.submitLoading = false;
          this.dialogAutoDrawChooseSeed.visible = false;
        }, error => {
          this.dialogAutoDrawChooseSeed.submitLoading = false;
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
        });
      });
    },
    // 设置种子
    setSeed(row) {
      console.log(row);
      this.dialogAutoDrawChooseSeed.submitLoading = true;
      api_PUT_EventsManagementEntryEntrySeedEntryId(
        row.entryId,
        { seed: null }
      ).then(res => {
        this.handleAutoDraw(this.tableRow);
        this.$message({ type: 'success', message: '操作成功' });
        this.dialogAutoDrawChooseSeed.submitLoading = false;
        this.dialogAutoDrawChooseSeed.visible = false;
      }, error => {
        this.dialogAutoDrawChooseSeed.submitLoading = false;
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    // 提交 —— 自动抽签  type 一键=all；批量=batch； 单行=row；
    handleSubmitAutoDraw(arr, type) {
      if (type !== 'row') {
        let flagTips = false;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].registerCount === 0 || arr[i].registerCount === 1) {
            flagTips = true;
            break;
          }
        }
        if (flagTips) {
          this.$confirm(`选中的项目中含有1人的项目，您确定继续抽签吗？`, '提示', {
            confirmButtonText: translateByCode('alert.confirm'),
            cancelButtonText: translateByCode('alert.cancel'),
            type: 'warning'
          }).then(() => {
            this.submitAutoDraw(arr, type);
          });
        } else {
          this.submitAutoDraw(arr, type);
        }
      } else {
        this.submitAutoDraw(arr, type);
      }
    },
    // 一键抽签
    handleAllDraw() {
      const _this = this;
      const _input = {
        categoryId: this.currentcategoryID,
        isTeamMemberNeedToAvoid: true // 一键抽签时isSeedNeedToAvoid 为true 杜龙
      };
      api_POST_EventsManagementDrawLotsAppSeviceBatchDraw(_input).then(res => {
        this.getPageData();
        this.dialogAutoDraw.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
        // this.drawLoading = false;
        _this.fullscreenLoading.close();
      }, error => {
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
        // this.drawLoading = false;
        _this.fullscreenLoading.close();
      }).catch((error) => {
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
        // this.drawLoading = false;
        _this.fullscreenLoading.close();
      });
    },
    submitAutoDraw(arr, type) {
      this.loading = true;
      if (this.competitiveType === 'Competitive') {
        const _input = {
          eventsId: type === 'row' ? [this.tableRow.eventId] : arr.map(res => res.eventId),
          isTeamMemberNeedToAvoid: this.isTeamMemberNeedToAvoid,
          isSeedNeedToAvoid: type === 'row' // 批量抽签调用接口时isSeedNeedToAvoid 为false,自动抽签为true 杜龙
        };
        api_POST_EventsManagementDrawLotsAppSeviceAutoCompetitiveDraw(_input).then(res => {
          this.getPageData();
          this.dialogAutoDraw.visible = false;
          this.$message({ type: 'success', message: '操作成功' });
          this.loading = false;
        }, error => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
          this.loading = false;
        }).catch((error) => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
          this.loading = false;
        });
      }
      if (this.competitiveType === 'NoneCompetitive') {
        const _eventsId = {
          eventsId: type === 'row' ? [this.tableRow.eventId] : arr.map(res => res.eventId)
        };
        api_POST_EventsManagementDrawLotsAppSeviceAutoNoneCompetitiveDraw(_eventsId).then(res => {
          this.getPageData();
          this.dialogAutoDraw.visible = false;
          this.$message({ type: 'success', message: '操作成功' });
          this.loading = false;
        }, error => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
          this.loading = false;
        });
      }
    },
    /**
     * 手动抽签
     * @param {object} row 操作单行数据的row值
    */
    handleManualDraw(row) {
      this.tableRow = row;
      this.isEidtDraw = false;
      console.log(row);
      // 处理签位号
      this.dialogManualDraw.lotCount = [];
      for (let i = 0; i < row.registerCount; i++) {
        this.dialogManualDraw.lotCount.push({
          lot: i + 1,
          disabled: false
        });
      }
      this.getEntryRegistersData(row).then(res => {
        this.dialogManualDraw.tableData = res.items;
        for (let i = 0; i < this.dialogManualDraw.tableData.length; i++) {
          const item = this.dialogManualDraw.tableData[i];
          if (item.registerNames && item.registerNames.length > 0) {
            for (let j = 0; j < item.registerNames.length; j++) {
              if (j === 0) {
                item.competitionRegisterName = item.registerNames[j];
              } else {
                item.competitionRegisterName += '/' + item.registerNames[j];
              }
            }
          }
        }
        this.initAgainstDataByManual();
        this.dialogManualDraw.visible = true;
      });
    },
    /**
     * 编辑抽签
     * @param {object} row 操作单行数据的row值
    */
    changeManualDraw(row) {
      const _this = this;
      if (row.isEditable) {
        this.tableRow = row;
        this.isEidtDraw = true;
        // 处理签位号
        this.dialogManualDraw.lotCount = [];
        api_GET_EventsManagementDrawLotsAppSeviceDrawLotsResultEventId(row.eventId).then(res => {
          // 过滤掉没有数据的值
          this.drawLotsResult = res.filter((item) => {
            if (item.competitionRegisterId) {
              return item;
            }
          });
          // 先放入已抽签的人的签号
          for (let i = 0; i < _this.drawLotsResult.length; i++) {
            this.dialogManualDraw.lotCount.push({
              lot: i + 1,
              disabled: true
            });
          }
          this.getUndrawnEntryRegisters(row).then(res1 => {
            // 后放入新报名的人可选的签号
            _this.undrawnEntryRegisters = res1;
            for (let i = 0; i < res1.length; i++) {
              _this.dialogManualDraw.lotCount.push({
                lot: _this.drawLotsResult.length + i + 1,
                disabled: false
              });
            }
            _this.drawLotsResult = _this.drawLotsResult.sort((a, b) => a.lotNumber - b.lotNumber);
            _this.dialogManualDraw.tableData = [..._this.drawLotsResult, ...res1];
            for (let i = 0; i < _this.dialogManualDraw.tableData.length; i++) {
              const item = _this.dialogManualDraw.tableData[i];
              if (item.registerNames && item.registerNames.length > 0) {
                for (let j = 0; j < item.registerNames.length; j++) {
                  if (j === 0) {
                    item.competitionRegisterName = item.registerNames[j];
                  } else {
                    item.competitionRegisterName += '/' + item.registerNames[j];
                  }
                }
              }
            }
            console.log(_this.dialogManualDraw.tableData);
            this.initAgainstDataByManualForEdit();
            this.dialogManualDraw.visible = true;
          });
        }, (error) => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      } else {
        this.$message({ type: 'warning', message: '此项目已开赛，不能进行编辑操作！' });
      }
    },
    // 按体重拆分
    handleDrawweightSplit () {
      if (this.multipleSelection.length === 0) {
          this.$message({ type: 'warning', message: '请至少先勾选一条数据，再进行操作！' });
          return;
      }
      const eventIds = [];
      // this.multipleSelection.map(item => item.eventId);
        this.multipleSelection.map(res => {
          eventIds.push(res.eventId)
        })
      api_POST_EventsManagementEventIsNotWeight({'eventIds': eventIds}).then(res => {
        if(res) {
          this.$confirm(`所选项目中包含无体重数据选手（未称重、体重未通过或资格审核未通过），是否继续进行批量拆分？`, '批量拆分（按体重）', {
            confirmButtonText: translateByCode('alert.confirm'),
            cancelButtonText: translateByCode('alert.cancel'),
            type: 'warning'
          }).then(() => {
            this.titleweight = '批量拆分(按体重)'
            this.dialogDrawSplit.batchVisible = true;

          });
        } else {
          this.titleweight = '批量拆分(按体重)'
          this.dialogDrawSplit.batchVisible = true;
        }
      }, error => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
        })
    },
    // 编辑抽签里的初始化对阵图
    initAgainstDataByManualForEdit() {
      const _this = this;
      const tableData = JSON.parse(JSON.stringify(this.drawLotsResult));
      const lotCountLength = this.drawLotsResult.length;
      let _len = 0;
      for (let i = 0; i < this.matchMap.length; i++) {
        if (lotCountLength <= this.matchMap[i]) {
          // eslint-disable-next-line no-const-assign
          _len = this.matchMap[i];
          break;
        }
      }
      //  判断竞技的编辑里新报名的人员是否超过了原先的对阵图人数
      if (_this.drawLotsResult.length + _this.undrawnEntryRegisters.length > _len) {
        _this.isOverNums = true;
      } else {
        _this.isOverNums = false;
      }
      console.log('isOverNums', _this.isOverNums);
      for (let i = 0; i < _len - _this.drawLotsResult.length; i++) {
        const againstItem = {
          approveStatusCode: '',
          avatar: '',
          competitionRegisterId: 'bye',
          competitionRegisterName: i + _this.drawLotsResult.length < lotCountLength ? '请选择运动员' : '轮空',
          delegationId: 'bye',
          delegationName: '',
          entryId: 'bye',
          eventId: 'bye',
          registerId: '',
          registerIdCardNumber: '',
          registerPhoneNumber: '',
          seed: '',
          lotNumber: i + 1 + this.drawLotsResult.length
        };
        tableData.push(againstItem);
      }
      this.dialogManualDraw.tableDataAgainst = tableData;
      this.handleAgainstData();
    },
    // 修改签号
    changeLots(e, row) {
      if (e) {
        const _lot = e;
        console.log(e);
        const _rowLot = row.lotNumber;
        if (_rowLot) {
          const _row = deepCopy(row);
          _row.competitionRegisterName = '';
          _row.delegationName = '';
          _row.avatar = '';
          this.handleAgainstDataByManual(_row);
          this.dialogManualDraw.lotCount[_rowLot - 1].disabled = false;
        }
        this.dialogManualDraw.lotCount[_lot - 1].disabled = true;
        this.$set(row, 'lotNumber', _lot);
        this.handleAgainstDataByManual(row);
      } else {
        const _row = deepCopy(row);
        _row.competitionRegisterName = '请选择运动员';
        _row.delegationName = '';
        _row.avatar = '';
        // _row.competitionRegisterName = '比赛人员';
        // _row.delegationName = '比赛团体';
        _row.avatar = '';
        const _rowLot = row.lotNumber;
        this.dialogManualDraw.lotCount[_rowLot - 1].disabled = false;
        this.$set(row, 'lotNumber', '');
        this.handleAgainstDataByManual(_row);
      }
    },
    // 初始化对阵图
    initAgainstDataByManual() {
      const tableData = [];
      const lotCountLength = this.dialogManualDraw.lotCount.length;
      let _len = 0;
      for (let i = 0; i < this.matchMap.length; i++) {
        if (lotCountLength <= this.matchMap[i]) {
          // eslint-disable-next-line no-const-assign
          _len = this.matchMap[i];
          break;
        }
      }
      for (let i = 0; i < _len; i++) {
        const againstItem = {
          approveStatusCode: '',
          avatar: '',
          competitionRegisterId: 'bye',
          competitionRegisterName: i < lotCountLength ? '请选择运动员' : '轮空',
          delegationId: 'bye',
          delegationName: '',
          entryId: 'bye',
          eventId: 'bye',
          registerId: '',
          registerIdCardNumber: '',
          registerPhoneNumber: '',
          seed: '',
          lotNumber: i + 1
        };
        tableData.push(againstItem);
      }
      this.dialogManualDraw.tableDataAgainst = tableData;
      this.handleAgainstData();
    },
    // 处理手动抽签对阵图数据
    handleAgainstDataByManual(row) {
      this.dialogManualDraw.tableDataAgainst[row.lotNumber - 1] = row;
      this.handleAgainstData();
    },
    // 对阵图数据处理
    handleAgainstData() {
      const againstData = this.dialogManualDraw.tableDataAgainst;
      const len = againstData.length;
      const leftData = againstData.slice(0, Math.round(len / 2));
      const rightData = againstData.slice(Math.floor(len / 2), len);
      const rLen = rightData.length;
      const leftTemporary = [];
      const rightTemporary = [];
      const returnAgainstData = [];
      for (let i = 0; i < leftData.length; i++) {
        if (i % 2 === 0) {
          leftTemporary.push([leftData[i], rightData[rLen - 1 - i]]);
        }
        if (i % 2 === 1) {
          rightTemporary.push([rightData[rLen - 1 - i], leftData[i]]);
        }
      }
      const rLenTemporary = rightTemporary.length;
      for (let i = 0; i < leftTemporary.length; i++) {
        leftTemporary[i].length > 0 && returnAgainstData.push(leftTemporary[i][0]);
        leftTemporary[i].length > 1 && returnAgainstData.push(leftTemporary[i][1]);
        if (rightTemporary[rLenTemporary - 1 - i] && rightTemporary[rLenTemporary - 1 - i].length > 0) {
          returnAgainstData.push(rightTemporary[rLenTemporary - 1 - i][0]);
        }
        if (rightTemporary[rLenTemporary - 1 - i] && rightTemporary[rLenTemporary - 1 - i].length > 1) {
          returnAgainstData.push(rightTemporary[rLenTemporary - 1 - i][1]);
        }
      }
      console.log(returnAgainstData);
      this.$set(this.dialogManualDraw, 'againstData', returnAgainstData);
      console.log('对阵图数据处理', this.dialogPreviewDraw.againstData);
    },
    handleSubmitDraw() {
      if (this.isEidtDraw) {
        this.handleEditManualDraw();
      } else {
        this.handleSubmitManualDraw();
      }
    },
    // 提交 —— 手动抽签
    handleSubmitManualDraw() {
      const _manualDrawInput = JSON.parse(JSON.stringify(this.dialogManualDraw.manualDrawInput));
      _manualDrawInput.eventId = this.tableRow.eventId;
      _manualDrawInput.items = [];
      for (let i = 0; i < this.dialogManualDraw.tableData.length; i++) {
        const item = this.dialogManualDraw.tableData[i];
        if (item.lotNumber) {
          _manualDrawInput.items.push({
            registerId: item.competitionRegisterId,
            lotNumber: item.lotNumber
          });
        } else {
          this.$message({ type: 'warning', message: '签号不能为空' });
          return;
        }
      }
      api_POST_EventsManagementDrawLotsAppSeviceManualCompetitiveDraw(_manualDrawInput).then(res => {
        this.getPageData(this.gameDrawQO.Page);
        this.dialogManualDraw.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    // 提交编辑抽签
    handleEditManualDraw() {
      const _manualDrawInput = JSON.parse(JSON.stringify(this.dialogManualDraw.manualDrawInput));
      _manualDrawInput.eventId = this.tableRow.eventId;
      _manualDrawInput.items = [];
      for (let i = 0; i < this.dialogManualDraw.tableData.length; i++) {
        const item = this.dialogManualDraw.tableData[i];
        if (item.lotNumber) {
          _manualDrawInput.items.push({
            registerId: item.competitionRegisterId,
            lotNumber: item.lotNumber
          });
        } else {
          this.$message({ type: 'warning', message: '签号不能为空' });
          return;
        }
      }
      api_PUT_EventsManagementDrawLotsAppSeviceDrawLots(_manualDrawInput).then(res => {
        this.getPageData(this.gameDrawQO.Page);
        this.dialogManualDraw.visible = false;
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: error.error && error.error.message || '' });
      });
    },
    /**
     * 预览
     * @param {object} row 操作单行数据的row值
    */
    handlePreview(row) {
      // 判断是否有铜牌赛
      // 判断是否是铜牌赛
      if (row.eventFormatCode === 'BronzeMedal') {
        this.eventFormat = true;
      } else {
        this.eventFormat = false;
      }

      // 判断团体、个人、双人
      this.registerTypeCode = row.registerTypeCode;
      this.titleName = row.categoryName + ' ' + row.groupName + row.gender.name + row.eventName;
      this.getDrawLotsResult(row).then(res => {
        if (this.competitiveType === 'Competitive') {
          // 竞技显示对阵图
          this.dialogPreviewDraw.againstData = res;
          for (let i = 0; i < this.dialogPreviewDraw.againstData.length; i++) {
            const item = this.dialogPreviewDraw.againstData[i];
            if (item.registerNames && item.registerNames.length > 0) {
              for (let j = 0; j < item.registerNames.length; j++) {
                if (j === 0) {
                  item.competitionRegisterName = item.registerNames[j];
                } else {
                  item.competitionRegisterName += '/' + item.registerNames[j];
                }
              }
            }
          }
        }
        if (this.competitiveType === 'NoneCompetitive') {
          // 非竞技显示表格
          this.dialogPreviewDraw.noneCompetitiveData = res;
          for (let i = 0; i < this.dialogPreviewDraw.noneCompetitiveData.length; i++) {
            const item = this.dialogPreviewDraw.noneCompetitiveData[i];
            if (item.registerNames && item.registerNames.length > 0) {
              for (let j = 0; j < item.registerNames.length; j++) {
                if (j === 0) {
                  item.competitionRegisterName = item.registerNames[j];
                } else {
                  item.competitionRegisterName += '/' + item.registerNames[j];
                }
              }
            }
          }
        }
        this.dialogPreviewDraw.visible = true;
        console.log('预览', this.dialogPreviewDraw.againstData);
      });
    },
    // 获取抽签结果
    getDrawLotsResult(row) {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementDrawLotsAppSeviceDrawLotsResultEventId(row.eventId).then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    /**
     * 获取项目报项人员/队伍列表
     * @param {object} row 操作单行数据的row值
    */
    getEntryRegistersData(row) {
      console.log(this.competitiveType);
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementEventIdEntryRegisters(row.eventId,
          {
            ApproveStatusCodes: 'ApproveSuccess',
            IsUsedForWeighing: !!(this.competitiveType === 'Competitive'),
            IsWeighingValid: !!(this.competitiveType === 'Competitive')
          }
        ).then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    /**
     * 获取未抽签项目报项人员/队伍列表
     * @param {object} row 操作单行数据的row值
    */
    getUndrawnEntryRegisters(row) {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementDrawLotsAppSeviceIdUndrawnEntryRegisters(row.eventId).then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 获取项目列表
    getEventList() {
      const eventVO = {};
      eventVO.CompetitionId = this.$route.params.id;
      eventVO.IncludeEventGroup = true;
      eventVO.IncludeEvent = true;
      eventVO.IncludeGender = true;
      eventVO.EventTypeCode = 'Competitive';
      api_GET_EventsManagementCategory(eventVO).then(res => {
        this.categoryDataForDown = res.items || [];
      }, () => {
        this.$message({ type: 'error', message: '获取项目列表失败！' });
      });
    },
    // 获取组别
    changeCategoryForDown(id) {
      this.eventValue.GroupId = '';
      const groupData = this.categoryDataForDown.filter((item) => {
        return item.id === id;
      });
      this.groupData = groupData[0] ? groupData[0].eventGroups : [];
      this.handleClear('group');
    },
    // 获取性别
    changeGroup(id) {
      var that = this;
      that.eventValue.Gender = '';
      if (id !== '') {
        const event = that.groupData.filter((item) => {
          return item.id === id;
        });
        const gender = event[0].events.map((item) => {
          var value = '';
          for (let j = 0; j < that.dict.gender.length; j++) {
            var jtem = that.dict.gender[j];
            if (item.genderCode === jtem.code) {
              value = jtem.code;
            }
          }
          return value;
        });
        const genderList = Array.from(new Set(gender)) || [];
        that.gender = genderList.map((item) => {
          var genderItem = '';
          for (let j = 0; j < that.dict.gender.length; j++) {
            var jtem = that.dict.gender[j];
            if (item === jtem.code) {
              genderItem = jtem;
            }
          }
          return genderItem;
        });
      }
      this.handleClear('gender');
    },
    // 获取级别
    changeGender(code) {
      var that = this;
      that.eventValue.EventId = '';
      if (that.eventValue.GroupId !== '') {
        const eventData = that.groupData.filter((item) => {
          return item.id === this.eventValue.GroupId;
        });
        const events = eventData[0].events.filter((item) => {
          item.name = item.name ? item.name : item.longName;
          return item.genderCode === code;
        });
        that.eventDataForDown = events;
      }
    },
    // 先选项目，再选组别
    judge(code) {
      if (this.eventValue.CategoryId === '') {
        this.$message({
          type: 'warning',
          message: '请先选择项目！'
        });
      } else if (code !== 'category' && this.eventValue.GroupId === '') {
        this.$message({
          type: 'warning',
          message: '请先选择组别！'
        });
      } else if (code !== 'group' && code !== 'category' && this.eventValue.Gender === '') {
        this.$message({
          type: 'warning',
          message: '请先选择性别！'
        });
      }
    },
    handleClear(code) {
      if (code === 'category') {
        this.eventValue = {
          CategoryId: '',
          GroupId: '',
          Gender: '',
          EventId: ''
        };
      } else if (code === 'group') {
        this.eventValue.GroupId = '';
        this.eventValue.Gender = '';
        this.eventValue.EventId = '';
      } else if (code === 'gender') {
        this.eventValue.Gender = '';
        this.eventValue.EventId = '';
      }
    },
    // 对阵表
    downloadBracket(reportName) {
      const _this = this;
      if (this.eventValue.CategoryId === '') {
        this.$message({ type: 'warning', message: '请选择项目级别！' });
        return;
      }
      const reportVO = {};
      reportVO.ReportName = reportName;
      reportVO.Format = 'PDF';
      reportVO.CategoryId = this.eventValue.CategoryId;
      reportVO.EventGroupId = this.eventValue.GroupId;
      reportVO.EventId = this.eventValue.EventId;
      reportVO.GenderCode = this.eventValue.Gender;
      reportVO.HasMatchCode = 0;
      this.downloadBracketLoadding = true;
      const fileName = '对阵表（带场次）' + '.pdf';
      const tempUrl = `/api/app/events-management/report`;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, reportVO).then(res => {
        _this.downloadBracketLoadding = false;
      }).catch(error => {
        _this.downloadBracketLoadding = false;
        console.log(error);
        errorText(error).then(function(text) {
          _this.$message({ type: 'error', message: text });
        });
      });
    },
    weightingCheck (row) {
      this.$refs.weightingCheck.open(row, this.CategoryId);
    },
    // 生成excel表
    downExcel(name) {
      const _this = this;
      this.downloadResultLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '级别合并表' + '.xlsx';
      const _vo = {
        ReportName: name,
        CompetitionId: this.$route.params.id,
        ProviderNames: 'C' // 修改的动作来源：M修改报项；C合并项目；S拆分项目
      };
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, _vo).then(res => {
        _this.downloadResultLoading = false;
      }).catch(error => {
        console.log('error', error);
        _this.downloadResultLoading = false;
        errorText(error).then(function(text) {
          _this.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>

.report_box {
  border:1px solid #eee;
  padding: 0 15px;
}
.el-table .cell .el-button {
  padding: 4px;
}
.preview_index {
  width: 34px;
  text-align: right;
  overflow: hidden;
}
.preview_top,
.preview_bottom {
  cursor: pointer;
  font-size: 16px;
}

.preview_top:hover,
.preview_bottom:hover {
  color: #5CBDFF;
}
.title_nanme{
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}
.PDFimg{
  height: 28px;
  width: 25px;
  vertical-align: middle;
}
.pdf_btn{
  cursor: pointer;
  display: inline-block;
}
.pdf_btn>span{
  padding-left: 5px;
  display: inline-block;
  vertical-align: middle;
}
.pdf_btn:hover span{
  color: #1890ff;
}
</style>
